/* 
 * Copyright 2013 Sébastien Mouquet.
 * 
 * This file is part of ECovoiturage.
 * 
 * ECovoiturage is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ECovoiturage is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ECovoiturage. If not, see http://www.gnu.org/licenses/.
 */
package com.smouquet.ecovoiturage.ui.page.root.moncompte;

import com.smouquet.ecovoiturage.ApplicationContext;
import com.smouquet.ecovoiturage.core.domain.Entreprise;
import com.smouquet.ecovoiturage.core.domain.Utilisateur;
import com.smouquet.ecovoiturage.core.service.EntrepriseService;
import com.smouquet.ecovoiturage.core.service.UtilisateurService;
import com.smouquet.ecovoiturage.ui.NotificationUtil;
import com.smouquet.ecovoiturage.ui.page.root.moncompte.MonCompteForm.SaveAccountEvent;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.VerticalLayout;
import java.util.List;

/**
 *
 * @author sebastien.mouquet
 */
public class MonCompteEditView extends VerticalLayout
                               implements View, MonCompteForm.SaveAccountListener
{
    public static final String VIEW_NAME = "moncompte/edit";
    
    public MonCompteEditView() {}
    

    @Override
    public void enter(ViewChangeEvent event)
    {
        Utilisateur currentUtilisateur = getSession().getAttribute(Utilisateur.class);
        
        EntrepriseService service = ApplicationContext.getInstance(EntrepriseService.class);
        List<Entreprise> entreprises = service.getAllOrderByNom();
        
        MonCompteForm form = new MonCompteForm(currentUtilisateur, entreprises);
        form.addSaveAccountListener(this);
        addComponent(form);
        
        setSizeFull();
        setMargin(true);
        setSpacing(true);
    }

    
    @Override
    public void onSaveAccount(SaveAccountEvent event)
    {
        doSauvegarder(event.getUtilisateur());
        
        NotificationUtil.showInformationNotification("Modifications enregistrées");
    }
    
    
    private void doSauvegarder(Utilisateur utilisateur)
    {
        UtilisateurService service = ApplicationContext.getInstance(UtilisateurService.class);
        
        Utilisateur u = service.updateUtilisateur(utilisateur);
        
        getSession().setAttribute(Utilisateur.class, u);
    }
}
